package fr.sedoo.commons.server.news.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import fr.sedoo.commons.client.DefaultApplication;
import fr.sedoo.commons.client.news.service.MessageService;
import fr.sedoo.commons.client.util.ServiceException;
import fr.sedoo.commons.client.util.StringUtil;
import fr.sedoo.commons.server.news.dao.MessageDAO;
import fr.sedoo.commons.server.storedfile.TmpFileManager;
import fr.sedoo.commons.server.storedfile.dao.StoredFileDAO;
import fr.sedoo.commons.shared.domain.Message;
import fr.sedoo.commons.shared.domain.StoredFile;
import fr.sedoo.commons.shared.domain.message.MessageDTO;
import fr.sedoo.commons.shared.domain.message.MessageTableItem;
import fr.sedoo.commons.shared.domain.message.TitledMessage;

public class MessageServiceImpl extends RemoteServiceServlet implements MessageService {

	MessageDAO dao;
	StoredFileDAO storedFileDAO;

	@Override
	public MessageDTO getMessageContentByUuid(String uuid) throws ServiceException {

		initDao();
		MessageDTO result = dao.findMessageContentByUuid(uuid);
		StoredFile storedFile = storedFileDAO.findByAttacherUuid(uuid);
		result.setFileName(storedFile.getName());
		return result;
	}

	@Override
	public TitledMessage getConsultMessageContentByUuid(String uuid, String preferredLanguage, List<String> alternateLanguages) throws ServiceException {
		initDao();
		return dao.getConsultMessageContentByUuid(uuid, preferredLanguage, alternateLanguages);
	}

	private void initDao() {
		if (dao == null) {
			dao = (MessageDAO) DefaultApplication.getSpringBeanFactory().getBeanByName(MessageDAO.BEAN_NAME);
		}
		if (storedFileDAO == null) {
			storedFileDAO = (StoredFileDAO) DefaultApplication.getSpringBeanFactory().getBeanByName(StoredFileDAO.BEAN_NAME);
		}
	}

	@Override
	public String saveMessage(String uuid, String author, HashMap<String, TitledMessage> content, String externaImagelUrl, String illustrationImageType, String fileName, boolean isTmpFile)
			throws ServiceException {

		initDao();
		if (uuid.length() == 0) {
			// creation
			uuid = UUID.randomUUID().toString();
			if (illustrationImageType.compareToIgnoreCase(Message.INTERNAL_IMAGE) == 0) {
				// We store the image
				StoredFile storedFile = new StoredFile();
				storedFile.setName(fileName);
				storedFile.setAttacherUuid(uuid);
				try {
					storedFile.setContent(TmpFileManager.getBytesForFile(fileName));
				} catch (Exception e) {
					throw new ServiceException(e.getMessage());
				}
				storedFileDAO.save(storedFile);
				TmpFileManager.removeTmpFile(fileName);
			}
		} else {
			// On supprime toutes les anciennes valeurs
			dao.deleteMessageByUuid(uuid);
			if (illustrationImageType.compareToIgnoreCase(Message.INTERNAL_IMAGE) != 0) {
				// We must delete any existing stored file
				storedFileDAO.deleteStoredFileByAttacherUuid(uuid);
			} else {
				if (isTmpFile) {
					// We must delete any existing stored file
					storedFileDAO.deleteStoredFileByAttacherUuid(uuid);
					StoredFile storedFile = new StoredFile();
					storedFile.setName(fileName);
					storedFile.setAttacherUuid(uuid);
					try {
						storedFile.setContent(TmpFileManager.getBytesForFile(fileName));
					} catch (Exception e) {
						throw new ServiceException(e.getMessage());
					}
					storedFileDAO.save(storedFile);
					TmpFileManager.removeTmpFile(fileName);
				} else {
					// We've got nothing to do the image is unchanged
				}
			}
		}
		Iterator<String> iterator = content.keySet().iterator();
		Date date = new Date();
		while (iterator.hasNext()) {
			String language = iterator.next();
			TitledMessage titledMessage = content.get(language);
			Message aux = new Message();
			aux.setContent(StringUtil.trimToEmpty(titledMessage.getContent()));
			aux.setTitle(StringUtil.trimToEmpty(titledMessage.getTitle()));
			aux.setLanguage(language);
			aux.setAuthor(author);
			aux.setDate(date);
			aux.setUuid(uuid);
			aux.setIllustrationImageType(illustrationImageType);
			aux.setExternaImagelUrl(StringUtil.trimToEmpty(externaImagelUrl));
			dao.save(aux);
		}

		return uuid;
	}

	@Override
	public ArrayList<MessageTableItem> getTitles(String preferredLanguage, List<String> alternateLanguages) throws ServiceException {
		ArrayList<MessageTableItem> result = new ArrayList<MessageTableItem>();
		initDao();

		ArrayList<String> uuids = dao.getUuids();
		for (String uuid : uuids) {
			TitledMessage aux = dao.getConsultMessageContentByUuid(uuid, preferredLanguage, alternateLanguages);
			result.add(new MessageTableItem(uuid, aux.getTitle(), aux.getAuthor(), aux.getDate()));
		}
		return result;
	}

	@Override
	public void deleteMessageByUuid(String uuid) throws ServiceException {
		initDao();
		dao.deleteMessageByUuid(uuid);
		storedFileDAO.deleteStoredFileByAttacherUuid(uuid);
	}

	@Override
	public ArrayList<TitledMessage> getAllTitledMessage(String preferredLanguage, List<String> alternateLanguages) throws ServiceException {
		ArrayList<TitledMessage> result = new ArrayList<TitledMessage>();
		initDao();

		ArrayList<String> uuids = dao.getUuids();
		for (String uuid : uuids) {
			result.add(dao.getConsultMessageContentByUuid(uuid, preferredLanguage, alternateLanguages));
		}
		return result;
	}

}
